using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [Header("Movement Settings")]
    [Tooltip("How fast the player moves")]
    public float moveSpeed = 5f;

    // Reference to the Rigidbody component
    private Rigidbody rb;

    // Called when the script instance is being loaded
    private void Awake()
    {
        // Get the Rigidbody component attached to this GameObject
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    private void Update()
    {
        // Get input from WASD keys
        float horizontalInput = Input.GetAxisRaw("Horizontal"); // A and D
        float verticalInput = Input.GetAxisRaw("Vertical");     // W and S

        // Calculate movement direction
        Vector3 movementDirection = new Vector3(horizontalInput, 0f, verticalInput).normalized;

        // Apply movement to the Rigidbody
        if (movementDirection != Vector3.zero)
        {
            // Calculate the velocity based on direction and speed
            Vector3 moveVelocity = movementDirection * moveSpeed;
            
            // Set the velocity of the Rigidbody
            rb.linearVelocity = new Vector3(moveVelocity.x, rb.linearVelocity.y, moveVelocity.z);
            
            // Optional: Rotate the player to face the movement direction
            transform.forward = movementDirection;
        }
        else
        {
            // Stop horizontal movement when no input is detected
            rb.linearVelocity = new Vector3(0f, rb.linearVelocity.y, 0f);
        }

        // Check for ESC key to quit the application
        if (Input.GetKeyDown(KeyCode.Escape))
        {
#if UNITY_EDITOR
            // In the editor, stop playing
            UnityEditor.EditorApplication.isPlaying = false;
#else
            // In a build, quit the application
            Application.Quit();
#endif
        }
    }
}
